package com.alex.core.redis;


import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.Duration;


@Configuration
@EnableCaching // 开启缓存支持
public class RedisConfig extends CachingConfigurerSupport {

    @Resource
    private LettuceConnectionFactory lettuceConnectionFactory;

    @Autowired
    private RedispProperties redispProperties;


    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
        om.enableDefaultTyping(DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //事务支持
        redisTemplate.setEnableTransactionSupport(true);
        setRedisTemplates(jackson2JsonRedisSerializer, redisTemplate);
        return redisTemplate;
    }

    private void setRedisTemplates(Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer, RedisTemplate<String, Object> redisTemplate) {
        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);// key序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
        redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
        redisTemplate.afterPropertiesSet();
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        // 配置redisTemplate
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
        om.enableDefaultTyping(DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //事务支持
        redisTemplate.setEnableTransactionSupport(true);
        return redisTemplate;
    }


    /**
     * 哨兵模式自动装配
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="spring.redisson.master-name")
    RedissonClient redissonSentinel() {
        String[] nodes = redispProperties.getSentinelAddresses();
        for(int i=0;i<nodes.length;i++) {
            nodes[i] = "redis://"+nodes[i];
        }
        Config config = new Config();
        SentinelServersConfig serverConfig = config.useSentinelServers()
                .addSentinelAddress(nodes)
                .setMasterName(redispProperties.getMasterName())
                .setTimeout(redispProperties.getMaxWait())
                .setMasterConnectionPoolSize(redispProperties.getMaxTotal())
                .setSlaveConnectionPoolSize(redispProperties.getMaxTotal());
        if(StringUtils.isNotBlank(redispProperties.getPassword())) {
            serverConfig.setPassword(redispProperties.getPassword());
        }
        return Redisson.create(config);
    }

    /**
     * 单机模式自动装配
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="spring.redisson.host",havingValue = "true")
    RedissonClient redissonSingle() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress("redis://" + redispProperties.getHostname() + ":" + redispProperties.getPort())
                .setTimeout(redispProperties.getMaxWait())
                .setConnectionPoolSize(redispProperties.getMaxTotal())
                .setConnectionMinimumIdleSize(redispProperties.getMinIdle());
        if(StringUtils.isNotBlank(redispProperties.getPassword())) {
            serverConfig.setPassword(redispProperties.getPassword());
        }
        return Redisson.create(config);
    }

    /**
     * 集群装配模式
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="spring.redisson.cluster.nodes")
    RedissonClient redissonCluster() {
        // String[] nodes = redispProperties.getCluster().get("nodes").split(",");
        String[] nodes = null;
        for(int i=0;i<nodes.length;i++) {
            nodes[i] = "redis://"+nodes[i];
        }
        Config config = new Config();
        ClusterServersConfig serverConfig = config.useClusterServers()
                .setScanInterval(2000)
                .addNodeAddress(nodes)
                .setTimeout(redispProperties.getMaxWait())
                .setMasterConnectionPoolSize(redispProperties.getMaxTotal())
                .setSlaveConnectionPoolSize(redispProperties.getMaxTotal())
                .setPassword(redispProperties.getPassword());
        if(StringUtils.isNotBlank(redispProperties.getPassword())) {
            serverConfig.setPassword(redispProperties.getPassword());
        }
        return Redisson.create(config);
    }

    @Override
    @Bean
    public RedisCacheManager cacheManager() {
        //方便观察数据，序列化成json格式
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);

        RedisSerializationContext.SerializationPair<Object> serializeValues = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
        //缓存的失效实现统一为2小时
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)).serializeValuesWith(serializeValues);
        return RedisCacheManager.builder(lettuceConnectionFactory).cacheDefaults(config).build();
    }
}